package cn.com.infohold.smartcity.activity;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;

import cn.com.infohold.smartcity.R;
import cn.com.infohold.smartcity.api.Dcms;
import cn.com.infohold.smartcity.api.HttpEvent;
import cn.com.infohold.smartcity.api.SDK;
import cn.com.infohold.smartcity.api.bean.LandResult;
import cn.com.infohold.smartcity.api.bean.LogInResult;
import cn.com.infohold.smartcity.api.bean.UserInfo;
import cn.com.infohold.smartcity.data.XmlConfig;
import cn.com.infohold.smartcity.data.XmlData;
import cn.com.infohold.smartcity.image.DrawableSelector;
import cn.com.infohold.smartcity.jpush.JPush;
import cn.com.infohold.smartcity.parent.ParentActivity;
import cn.com.infohold.smartcity.utils.GsonUtil;
import cn.com.infohold.smartcity.utils.RequestCode;
import cn.pedant.SweetAlert.SweetAlertDialog;
import common.annotation.ViewInject;
import common.dialog.ProgressDialog;
import common.listener.OnKeyBoardStateChangedListener;
import common.utils.ViewUtils;
import common.view.scroll.BounceScrollView;
import common.view.text.EditText;
import library.image.ImageUtils;
import library.utils.DisplayUtil;
import library.utils.Utils;


/**
 * Created by Mr.Fan on 2015/11/25.
 */
public class LoginActivity extends ParentActivity {

    @ViewInject(R.id.frgm_login_iv_avatar)
    private ImageView avatar;
    @ViewInject(R.id.frgm_login_et_username)
    private EditText et_username;
    @ViewInject(R.id.frgm_login_et_password)
    private EditText et_password;
    @ViewInject(R.id.frgm_login_btn_login)
    private Button btn_login;

    @Override
    protected Object inflateView() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView(View anchor) {
        JPush.unbind(getApplicationContext());
        setSystemBarTranslucent();

//        et_username.setHintSize(16);
//        et_password.setHintSize(16);
        et_username.setTextSize(20);
        et_password.setTextSize(20);
        btn_login.setTextSize(22);

        et_username.setBackgroundDrawable(DrawableSelector.getEditUnderBlue(this));
        et_password.setBackgroundDrawable(DrawableSelector.getEditUnderBlue(this));
        btn_login.setBackgroundDrawable(DrawableSelector.getLoginButton(this));

        final BounceScrollView sv = (BounceScrollView) findViewById(R.id.frgm_login_scroll);

        String logLabel = btn_login.getText().toString();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < logLabel.length(); i++) {
            sb.append(logLabel.charAt(i));
            if (i < logLabel.length() - 1) {
                sb.append("  ");
            }
        }
        btn_login.setText(sb.toString());

        ViewUtils.assistKeyboard(sv, new OnKeyBoardStateChangedListener() {
            @Override
            public void onStateChange(boolean b) {
                if (b) {
                    sv.scrollToBottom();
                }
            }
        });

        final int screen_width = DisplayUtil.getMetrics().widthPixels;
        final int screen_height = DisplayUtil.getMetrics().heightPixels;

        ViewGroup.MarginLayoutParams lp_log = (ViewGroup.MarginLayoutParams) avatar.getLayoutParams();
        lp_log.width = screen_width / 3;
        lp_log.height = lp_log.width;
        lp_log.topMargin = screen_width / 4;
        lp_log.bottomMargin = screen_width / 6;
        avatar.setLayoutParams(lp_log);

        ViewUtils.setEditNoCopyAndPaste(et_username);
        ViewUtils.setEditNoCopyAndPaste(et_password);

        int input_width = screen_width * 3 / 4;
        int input_height = input_width / 8;
        et_username.setMinimumHeight(input_height);
        et_password.setMinimumHeight(input_height);
        btn_login.setMinimumHeight(input_height);

        ViewGroup.MarginLayoutParams lp_et1 = (ViewGroup.MarginLayoutParams) et_username.getLayoutParams();
        lp_et1.width = input_width;
        et_username.setLayoutParams(lp_et1);
        ViewGroup.MarginLayoutParams lp_et2 = (ViewGroup.MarginLayoutParams) et_password.getLayoutParams();
        lp_et2.width = input_width;
        et_password.setLayoutParams(lp_et2);

        ViewGroup.MarginLayoutParams lp_btn = (ViewGroup.MarginLayoutParams) btn_login.getLayoutParams();
        lp_btn.width = input_width;
        btn_login.setLayoutParams(lp_btn);


        final Bitmap bm_clear = ImageUtils.obtain(this).resource(R.drawable.icon_clear).load();
        final Drawable clear = new BitmapDrawable(bm_clear);
        Bitmap bm_user = ImageUtils.obtain(this).resource(R.drawable.icon_user).load();
        Bitmap bm_pwd = ImageUtils.obtain(this).resource(R.drawable.icon_password).load();
        et_username.setInputDrawable(new BitmapDrawable(bm_user));
        et_username.setClearDrawable(clear);
        et_password.setInputDrawable(new BitmapDrawable(bm_pwd));
        et_password.setClearDrawable(clear);
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastTrigger())
                    return;
//                if (BuildConfig.ROLE == -1) {
//                    jumpToHome();
//                    return;
//                }
                hideKeyBoard();
                login(et_username.getText().toString(), et_password.getText().toString());
            }
        });


        et_username.setText(XmlData.getInstance().getUsername());
        UserInfo userInfo = XmlData.getInstance().getUserInfo();

        Bitmap bitmap = ImageUtils.obtain(this)
                .resource(R.drawable.icon_avatar_leader)
                .round()
                .load();
        avatar.setImageBitmap(bitmap);
        avatar.setScaleType(ImageView.ScaleType.FIT_CENTER);
        if (userInfo != null && !TextUtils.isEmpty(userInfo.getAvatar())) {
            if (!TextUtils.isEmpty(et_username.getText()))
                Dcms.loadAvatar(avatar, userInfo, true);

            et_username.setOnTextChanged(new EditText.OnTextChanged() {
                @Override
                public void onTextChanged(CharSequence text) {
                    if (text != null && text.toString().equals(XmlData.getInstance().getUsername())) {
                        Dcms.loadAvatar(avatar, userInfo, true);
                    } else {
                        Dcms.loadAvatar(avatar, null);
                    }
                }
            });

        }
//        Intent intent = getIntent();
//        if (intent != null && EventBus.OMPA_ACTION_MULTI_LONGIN.equals(intent.getAction())) {
//            MessageDialog.confirm(Activity_Login.this, getString(R.string.multi_login));
//            PushManager.cancelAll();
//        }
        if (!Utils.isNetworkAvailable(this)) {
            warn(getString(R.string.net_is_not_available));
        }

        XmlConfig.getInstance().setAutoLogin(false);
    }

    private void login(final String username,final String password){
        if (TextUtils.isEmpty(username) && TextUtils.isEmpty(password)) {
            warn(getString(R.string.error_login_null_unpwd));
        } else if (TextUtils.isEmpty(username)) {
            warn(getString(R.string.error_login_null_un));
        } else if (TextUtils.isEmpty(password)) {
            warn(getString(R.string.error_login_null_pwd));
        } else if (!Utils.isNetworkAvailable(this)) {
            warn(getString(R.string.net_is_not_available));
            return;
        } else{
            ProgressDialog.show(this);
            SDK.api().login(username,password).postEvent(RequestCode.REQUEST_CODE_GET_LOGIN);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getLoginData(HttpEvent<String> httpEvent){
        int requestCode = httpEvent.getRequestCode();
        if (requestCode != RequestCode.REQUEST_CODE_GET_LOGIN) {
            ProgressDialog.dismiss();
            return;
        }

        if (httpEvent.getState() != HttpEvent.STATE_SUCCESS) {
            ProgressDialog.dismiss();
            return;
        } else {
            switch (requestCode){
                case RequestCode.REQUEST_CODE_GET_LOGIN:

                    Type type = new TypeToken<LandResult<LogInResult<UserInfo>>>(){}.getType();
                    LandResult<LogInResult<UserInfo>> result = GsonUtil.fromJson(httpEvent.getData(),type);
                    switch (result.getStatus()){
                        case "1":
                            XmlData.getInstance().setUserInfo(result.getResult().getUserInfo());
                            XmlData.getInstance().setUsername(et_username.getText().toString());
                            XmlData.getInstance().setPassword(et_password.getText().toString());
                            XmlConfig.getInstance().setAutoLogin(true);

                            jumpToHome();
                            break;
                        case "2":
                            warn(result.getMessage());
                            break;
                    }

                    break;
                default:
                    break;
            }
        }
    }

//    private void login(final String username, final String password) {
//        if (TextUtils.isEmpty(username) && TextUtils.isEmpty(password)) {
//            warn(getString(R.string.error_login_null_unpwd));
//        } else if (TextUtils.isEmpty(username)) {
//            warn(getString(R.string.error_login_null_un));
//        } else if (TextUtils.isEmpty(password)) {
//            warn(getString(R.string.error_login_null_pwd));
//        } else if (!Utils.isNetworkAvailable(this)) {
//            warn(getString(R.string.net_is_not_available));
//            return;
//        } else {
//            SDK.api().login(username, password)
//                    .tag(this)
//                    .callback(new HttpCallback<LandResult<UserInfo>>() {
//
//                        @Override
//                        public void onStart() {
//                            btn_login.setEnabled(false);
//                            Animation animation = new AlphaAnimation(0.99f, 1);
//                            animation.setRepeatMode(Animation.RESTART);
//                            animation.setDuration(500);
//                            animation.setRepeatCount(Animation.INFINITE);
//                            animation.setAnimationListener(new Animation.AnimationListener() {
//                                private String bak = btn_login.getText().toString();
//                                private String text = bak.replace(" ", "");
//                                private String dot = "";
//
//                                @Override
//                                public void onAnimationStart(Animation animation) {
//                                    btn_login.setText(text + "");
//                                }
//
//                                @Override
//                                public void onAnimationEnd(Animation animation) {
//                                    btn_login.setText(bak + "");
//                                }
//
//                                @Override
//                                public void onAnimationRepeat(Animation animation) {
//                                    btn_login.setText(text + dot);
//                                    if (dot.length() >= 3) {
//                                        dot = "";
//                                    } else {
//                                        dot += ".";
//                                    }
//                                }
//                            });
//                            btn_login.startAnimation(animation);
//                        }
//
//                        @Override
//                        public void onFailure(Exception ex) {
//                            super.onFailure(ex);
//                            warn(getString(R.string.error_login_failed));
//                        }
//
//                        @Override
//                        protected void onCancel() {
//                            super.onCancel();
//                        }
//
//                        @Override
//                        protected void onTimeout(Exception e) {
//                            super.onTimeout(e);
//                            warn(getString(R.string.error_login_timeout));
//                        }
//
//                        @Override
//                        protected void onSuccess(LandResult<UserInfo> result) {
//                            super.onSuccess(result);
//                            switch (result.getStatus()){
//                                case "1":
//                                    UserInfo userInfo = result.getResult();
//                                    XmlData.getInstance().setUserInfo(userInfo);
//                                    XmlConfig.getInstance().setAutoLogin(true);
//
//                                    jumpToHome();
//                                    break;
//                                case "2":
//                                    warn(result.getMessage());
//                                    break;
//                                default:
//                                    break;
//                            }
//                        }
//
//                        @Override
//                        public void onFinish() {
//                            btn_login.setEnabled(true);
//                            btn_login.clearAnimation();
//                        }
//                    });
//        }
//    }

    private void jumpToHome() {
        Utils.startActivity(getApplicationContext(), HomePageActivity.class);
        finish();
    }

    @Override
    public void onBackPressed() {
//        moveTaskToBack(true);
        finish();
    }

    SweetAlertDialog mDialogWarn;

    public void warn(String message) {

        mDialogWarn = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                .setTitleText(message)
                .setContentText("")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismissWithAnimation();
                    }
                });
        mDialogWarn.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                mDialogWarn = null;
            }
        });
        mDialogWarn.show();
    }
}
